<template>
    <div>
        <div class="echart" :id="frequencyId + ''" :style="{ width: width, height: height }" @click="handleClick"
            ref="chartContainer"></div>

        <!-- <div class="ruler">
            <div class="mark" style="left: 10%;"></div>
            <div class="mark" style="left: 20%;"></div>
            <div class="mark" style="left: 30%;"></div>
            <div class="mark" style="left: 40%;"></div>
            <div class="mark" style="left: 50%;"></div>
            <div class="mark" style="left: 60%;"></div>
            <div class="mark" style="left: 70%;"></div>
            <div class="mark" style="left: 80%;"></div>
            <div class="mark" style="left: 90%;"></div>
        </div> -->
    </div>
</template>
  
<script>
import * as echarts from "echarts";
import Decimal from 'decimal.js';

export default {
    name: "Frequency",
    data() {
        return {
            number: null,
            expanded_data: [],
            corresponding_data: [],
            xAxisData: [],
            seriesData: [],
            x_coordinates: [],
            interval: 100, // 间隔长度
            frequencyId: this.generateUniqueId() + "frequencyId",
            option: null,
            chartDom: null,
            myChart: null,
            input_data: null,
        };
    },
    props: {
        inputData: {
            type: Object,
        },
        height: {
            type: String,
            default: '450px',
        },
        width: {
            type: String,
            default: '100%',
        },
        type: {//1-全频段，2下变频
            type: Number,
            default: 2
        }
    },
    watch: {
        inputData: function (val) {
            // this.expandData();
            this.input_data = val
            this.expandData();
            this.initEcharts();
        },

    },
    mounted() {
        this.chartDom = document.getElementById(this.$refs.chartContainer.id);
        this.input_data = this.inputData
        this.expandData();
        this.initEcharts();
    },
    created() {


    },
    methods: {
        generateUniqueId() {
            const timestamp = new Date().getTime().toString(16); // 时间戳的16进制表示
            const randomPart = Math.random().toString(16).substring(2); // 随机数的16进制表示，去掉0.
            const uniqueId = timestamp + randomPart;
            return uniqueId;
        },
        handleClick(params) {
            // const xAxisIndex = params.event;
            // console.log("seriesData");
            // console.log(this.seriesData);
            // console.log(params);
            // if (xAxisIndex >= 0 && xAxisIndex < this.xAxisData.length) {
            //     this.number = this.xAxisData[xAxisIndex];
            // }
            // console.log(this.number);

            // // 更新 number 值
            // this.setNumber();
        },

        divideArray() {
            // let arr = [this.input_data.central]
            // const numMath = Math.floor(num);

            // for (let i = 1; i <= numMath; i++) {
            //     arr.push(this.input_data.central + i * 1);
            //     arr.unshift(this.input_data.central - i * 1)
            // }
            // this.xAxisData = arr;
        },
        expandData() {
            // 将输入字符串转换为数组
            const dataArray = this.input_data.data.split(",").map(Number);
            // 使用线性插值将数据从原始点数扩展到所需点数
            //  const expandedData = this.interpolateData(dataArray, );
            // 更新扩展后的数据
            this.seriesData = dataArray
            // 计算每个值对应的数据
            this.divideArray()
        },
        interpolateData(dataArray, needPoints) {
            const originalPoints = dataArray.length;

            // 使用线性插值将数据从原始点数扩展到所需点数
            const expandedData = [];
            for (let i = 0; i < needPoints; i++) {
                const index = (i / (needPoints - 1)) * (originalPoints - 1);
                const lowerIndex = Math.floor(index);
                const upperIndex = Math.ceil(index);
                const t = index - lowerIndex;

                const interpolatedValue =
                    dataArray[lowerIndex] + t * (dataArray[upperIndex] - dataArray[lowerIndex]);

                expandedData.push(Math.round(interpolatedValue));
            }

            return expandedData;
        },

        calculateCorrespondingData(expandedData) {
            const centralIndex = this.input_data.central;
            const correspondingData = [];

            for (let i = 0; i < expandedData.length; i++) {
                const dataIndex = centralIndex + (i - expandedData.length / 2);
                correspondingData.push({ value: expandedData[i], dataIndex });
            }

            return correspondingData;
        },
        setNumber() {
            // console.log( this.number +","+this.input_data.bandwidth);
            console.log(this.number);
            this.$emit("setNumber", this.number);
        },
        handleMouseMove(event) {
            const myChart = echarts.getInstanceByDom(event.currentTarget);
            const xAxisIndex = myChart.convertFromPixel(this.$refs.chartContainer.id, [event.offsetX, event.offsetY])[0];

            if (xAxisIndex >= 0 && xAxisIndex < this.xAxisData.length) {
                this.number = this.xAxisData[xAxisIndex];
            }

            // 更新 number 值
            this.setNumber();
        },


        handleMouseOut() {
            // 鼠标移出时可以选择清空 number 的值或保留最后一个值
            // this.number = null;
            // 或者保留最后一个值
            // this.setNumber();
        },
        getCalibration(val, type) {
            const self = this
            
            if (type == 1) {
                return ((val * 1 * + parseInt(self.input_data.bandwidth / self.seriesData.length)))*2 + parseInt(self.input_data.central - self.input_data.bandwidth / 2)
            } else {
                return (val * 1 * + parseInt(self.input_data.bandwidth / self.seriesData.length)) + parseInt(self.input_data.central)
            }
        },
        initEcharts() {
            const self = this;
            const myChart = echarts.init(this.chartDom);
            this.option = {
                grid: {
                    top: "15%",
                    right: "10%",
                    left: "10%",
                    bottom: "15%",
                },
                xAxis: {
                    splitNumber: 5,
                    type: "category",
                    boundaryGap: false,
                    // data: this.xAxisData,
                    // default: 100,
                    axisLabel: {
                        interval: 49, // 刻度显示间隔
                        show: true,
                        formatter: function (value) {
                            // console.log("数组长度" + parseInt(self.seriesData.length));
                            // console.log("每一段长度：" + parseInt(self.input_data.central / self.seriesData.length));
                            // console.log("当前刻度线：" + value*1 );
                            // console.log("当前起点：" , self.input_data.central - self.input_data.bandwidth);
                            // const w = (value*1 * + parseInt(self.input_data.bandwidth / self.seriesData.length)) +  parseInt(self.input_data.central - self.input_data.bandwidth/2)
                            return self.getCalibration(value, self.type);
                        },
                    },
                    offset: 0,
                    axisLine: {
                        onZero: false,
                        lineStyle: {
                            color: 'white', // 刻度线颜色
                        },
                    },
                    axisTick: {//刻度线属性
                        // alignWithLabel: false,
                        // show: false,//刻度线显示
                        lineStyle: {
                            type: 'solid',
                            width: 2, // 设置刻度线宽度
                        },
                    },
                    minorTick: {
                        show: true,
                        splitNumber: 5,
                        length: 3,
                    },
                },
                yAxis: {
                    type: 'value',
                    min: -150, // 设置最小值
                    max: 60, // 设置最大值
                    interval: 10, // 设置分隔为5
                    axisLabel: {
                        margin: 30, // 设置刻度标签的宽度
                    },
                },
                series: {
                    data: this.seriesData,
                    type: "line",
                    lineStyle: {
                        color: "transparent", // 设置线条颜色为白色
                        color: "while", // 设置线条颜色为白色
                        opacity: 0.5,
                    },
                    areaStyle: {
                        color: "#857120", // 设置区域颜色为黄色
                        opacity: 0.5,
                        origin: 'start', // 设置区域样式从y轴的0开始
                    },
                    symbol: "none", // 设置折线上的点的图标为无
                    showSymbol: false, // 隐藏折线上的点
                    emphasis: {
                        focus: 'none', // 禁用悬浮效果
                    },
                    itemStyle: {
                        opacity: 0.5,
                    },
                },
            };
            myChart.getZr().on('click', function (param) {
                const pointInPixel = [param.offsetX, param.offsetY]
                // console.log('pointInPixel', pointInPixel)
                // 使用 convertFromPixel方法 转换像素坐标值到逻辑坐标系上的点。获取点击位置对应的x轴数据的索引值，借助于索引值的获取到其它的信息
                // 转换X轴坐标
                let pointInGrid = myChart.convertFromPixel({ seriesIndex: 0 }, pointInPixel);
                // 转换Y轴坐标
                // let pointInGrid2 = myChart.convertFromPixel({ seriesIndex: 1 }, pointInPixel);
                // x轴数据的索引值
                // console.log('pointInGrid', pointInGrid)
                // 所点击点的X轴坐标点所在X轴data的下标
                let xIndex = pointInGrid[0];
                // 所点击点的Y轴坐标点数值
                // let yIndex = pointInGrid2[1];
                // 使用getOption() 获取图表的option
                // let op = myChart.getOption();
                //获取到x轴的索引值和option之后，我们就可以获取我们需要的任意数据。
                // 点击点的X轴对应坐标的名称
                // console.log('pointInGrid', xIndex)
                // console.log('pointInGridAdd', xArr)
                // console.log('pointInGrid2',  xIndex)
                if (xIndex >= 0 && xIndex < self.seriesData.length) {
                    // self.number = self.seriesData[xIndex];
                    // const c = xIndex * (self.input_data.bandwidth / self.seriesData.length) + (self.input_data.central - self.input_data.bandwidth) 
                    // const c = (xIndex * 1 * + parseInt(self.input_data.bandwidth / self.seriesData.length)) + parseInt(self.input_data.central - self.input_data.bandwidth / 2)
                    // console.log('xINDEX:', self.input_data)
                    // console.log('数量:', self.seriesData.length)
                    // console.log("每一个点长度：",self.seriesData.length);  // console.log("数组长度：",self.seriesData.length);
                    self.number = self.getCalibration(xIndex, self.type);
                    // 更新 number 值
                    self.setNumber();
                }

            });

            this.option && myChart.setOption(this.option);
        },
        beforeDestroy() {
            // // 销毁 ECharts 实例，释放资源
            // if (this.myChart) {
            //     this.myChart.dispose();
            // }
        },
    },
};
</script>
  
<style rel="stylesheet/scss" lang="scss">
/* Your existing styles */

.ruler {
    position: relative;
    width: 300px;
    height: 50px;
    background-color: #f0f0f0;
    margin-top: 50px;
}

.ruler::before,
.ruler::after {
    content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    width: 1px;
    background-color: #333;
}

.ruler::before {
    left: 0;
}

.ruler::after {
    right: 0;
}

.mark {
    position: absolute;
    width: 1px;
    height: 10px;
    background-color: #333;
    top: 50%;
    transform: translateY(-50%);
}

.mark:nth-child(5n) {
    height: 20px;
    /* 长一些的刻度线，比如每5个刻度为一个大刻度 */
}
</style>
  